package com.yidiandao.business.ui.main.shoppingcart.confirmorder;

import com.yidiandao.business.R;
import com.yidiandao.business.data.Consignee;
import com.yidiandao.business.data.event.RefreshGoodsDetailEvent;
import com.yidiandao.business.data.model.IConfirmOrderModel;
import com.yidiandao.business.data.response.QueryConfirmOrderDataResponse;
import com.yidiandao.business.data.response.SubmitOrderResponse;
import com.yidiandao.business.manager.GiftManager;
import com.yidiandao.business.manager.ReduceManager;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 新的确认订单页面 Presenter
 */
public class ConfirmOrderPresenter implements ConfirmOrderContract.Presenter {

    private ConfirmOrderContract.View mConfirmOrderView;

    private IConfirmOrderModel mConfirmOrderModel;

    private List<String> mPayWays;

    public ConfirmOrderPresenter(ConfirmOrderContract.View view, IConfirmOrderModel confirmOrderModel) {
        mConfirmOrderView = view;
        mConfirmOrderModel = confirmOrderModel;

        mConfirmOrderView.setPresenter(this);
    }

    @Override
    public void start() {
        loadConfirmOrderData();
    }

    @Override
    public void loadConfirmOrderData() {
        mConfirmOrderModel.loadOthersConfirmOrderData(mConfirmOrderView.getPagerTag(), new IConfirmOrderModel.OnConfirmOrderResponseListener() {

            @Override
            public void onSuccess(QueryConfirmOrderDataResponse response) {

                mConfirmOrderView.refreshContent(SuperLoadingLayout.STATE_SUCCESS);

                QueryConfirmOrderDataResponse.Data data = response.getData();

                handleConsignee(data);
                handleGoodsList(data, data.getTotalFee().getTotalGoodsNumber());
                handlePayWay(data);
                handleInvoice(data);
                handleServicePhone(data);
                handleRedPacket(data.getTotalFee());
                handleCoupon(data.getCouponCount(), data.getCouponMoney(), data.getTotalFee());
                handleTotalFee(data.getTotalFee());
            }

            // 优惠券
            private void handleCoupon(int couponCount, float couponMoney, QueryConfirmOrderDataResponse.TotalFee totalFee) {
                mConfirmOrderView.refreshCoupon(couponCount, couponMoney);
                totalFee.setCoupon(couponMoney);
            }

            // 收货人相关信息
            private void handleConsignee(QueryConfirmOrderDataResponse.Data data) {
                Consignee consignee = data.getConsignee();
                mConfirmOrderView.refreshConsignee(consignee);
            }

            // 商品列表
            private void handleGoodsList(QueryConfirmOrderDataResponse.Data data, int totalGoodsNumber) {
                List<String> goodsList = data.getGoodsImages();
                mConfirmOrderView.refreshGoodsImages(goodsList, totalGoodsNumber);
            }

            // 支付方式
            private void handlePayWay(QueryConfirmOrderDataResponse.Data data) {
                mPayWays = data.getPayWays();
                StringBuilder builder = new StringBuilder();
                for (int i = 0, len = mPayWays.size(); i < len; i++) {
                    String payWay = mPayWays.get(i);
                    if (!builder.toString().contains(payWay)) {
                        builder.append(payWay);
                        if (i != len - 1) {
                            builder.append("、");
                        }
                    }
                }
                String showPayWays = builder.toString();

                if (showPayWays.lastIndexOf("、") == builder.length() - 1) {
                    showPayWays = showPayWays.substring(0, builder.length() - 1);
                }

                mConfirmOrderView.setPayWayUI(showPayWays, 0);
            }

            // 发票相关
            private void handleInvoice(QueryConfirmOrderDataResponse.Data data) {
                String invRate = data.getInvRate();
                String invTitle = data.getInvTitle();
                mConfirmOrderView.refreshInvoiceUI(invRate, invTitle);
            }

            // 客服电话
            private void handleServicePhone(QueryConfirmOrderDataResponse.Data data) {
                mConfirmOrderView.showServicePhone(data.getServicePhone());
            }

            // 处理红包
            private void handleRedPacket(QueryConfirmOrderDataResponse.TotalFee totalFee) {

                float redPacketReduce = totalFee.getRedPacket();
                int redPacketCount = totalFee.getRedPacketCount();

                // 刷新红包UI
                mConfirmOrderView.refreshRedPacketUI(redPacketReduce, redPacketCount);
            }

            private void handleTotalFee(QueryConfirmOrderDataResponse.TotalFee totalFee) {
                // 统计信息

                // 支付手续费
                float payFee = totalFee.getPayFee();
                // 默认选择的红包的费用
                float redPacket = totalFee.getRedPacket();
                // 优惠券
                float coupon = totalFee.getCoupon();

                // 运费
                float shippingFee = totalFee.getShippingFee();
                // 发票费用
                float invMoney = totalFee.getInvMoney();
                // 商品的总价格
                float goodsTotalPrice = totalFee.getGoodsTotalPrice();

                // 总价计算
                float submitPrice = goodsTotalPrice + payFee + shippingFee + invMoney - redPacket - coupon;

                mConfirmOrderView.refreshTotalFeeUI(goodsTotalPrice, shippingFee, invMoney, payFee, submitPrice);
            }

            @Override
            public void onFailed() {
                mConfirmOrderView.refreshContent(SuperLoadingLayout.STATE_ERROR);
            }
        });
    }

    @Override
    public void setNeedRefreshShoppingCart(boolean refreshShoppingCart) {
        mConfirmOrderModel.setNeedRefreshShoppingCart(refreshShoppingCart);
    }

    @Override
    public void toChooseDeliveryActivity() {
        mConfirmOrderView.toChooseDeliveryActivity(null);
    }

    @Override
    public void submitOrder() {
        mConfirmOrderView.showLoadingDialog();
        mConfirmOrderModel.submitOrder(mConfirmOrderView.getPagerTag(), mConfirmOrderView.getMessage(),
                new IConfirmOrderModel.OnSubmitOrderListener() {
                    @Override
                    public void onSuccess(SubmitOrderResponse response) {

                        mConfirmOrderView.hideLoadingDialog();

                        String orderPayId = response.getData().getOrderPayId();
                        String url = response.getData().getUrl();
                        // 在线支付的总金额
                        String totalOnlinePay = response.getData().getTotalOnlinePay();

                        // 不需要区分来自购物车或者非购物车
                        // 如果来自购物车,则清空购物车中的所有赠品
                        GiftManager.getInstance().clearAllFavourableInfoList();
                        ReduceManager.getInstance().clearAllReduce();


                        // 订单结算成功刷新购物车
                        setNeedRefreshShoppingCart(true);
                        //通知刷新商品详情
                        EventBus.getDefault().post(new RefreshGoodsDetailEvent());

                        mConfirmOrderView.finishActivity();

                        int otherPayWayCount = 0;

                        // 默认非在线支付
                        boolean hasOnlinePay = false;

                        // 判断支付方式
                        for (String payWay : mPayWays) {
                            if (UIUtils.getString(R.string.online_pay).equals(payWay)) {
                                // 在线支付
                                hasOnlinePay = true;
                            } else {
                                // 非在线支付
                                // 其他支付方式的数量增加
                                otherPayWayCount++;
                            }
                        }

                        // 根据支付方式的不同，去到不同的页面
                        if (!hasOnlinePay) {
                            // 不包含在线支付 --> 直接去订单结果页面
                            mConfirmOrderView.toOrderResultActivity(orderPayId);
                        } else if (otherPayWayCount == 0) {
                            // 全部都是在线支付 --> 去收银台
                            mConfirmOrderView.toCashierActivity(url, orderPayId, totalOnlinePay, true);
                        } else {
                            // 部分在线支付，部分其他支付 --> 去确认多种支付方式页面
                            mConfirmOrderView.toMultiPayWaysActivity(orderPayId);
                        }
                    }

                    @Override
                    public void onFailed() {
                        mConfirmOrderView.hideLoadingDialog();
                    }
                });
    }
}
